<template>
  <view class="member-container">
    <!-- 顶部导航栏 -->
    <view class="header">
      <view class="header-content">
        <text class="header-title">会员管理</text>
        <view class="header-actions">
          <uni-icons type="search" size="20" color="#fff" @click="toggleSearch" />
        </view>
      </view>
    </view>

    <!-- 数据概览卡片 -->
    <view class="overview-section">
      <view class="overview-card">
        <view class="overview-item">
          <text class="overview-value">{{ statistics.totalMembers || 0 }}</text>
          <text class="overview-label">会员总数</text>
        </view>
        <view class="overview-item">
          <text class="overview-value">{{ statistics.activeMembers || 0 }}</text>
          <text class="overview-label">活跃会员</text>
        </view>
        <view class="overview-item">
          <text class="overview-value">{{ statistics.newMembersToday || 0 }}</text>
          <text class="overview-label">今日新增</text>
        </view>
      </view>
    </view>

    <!-- 搜索栏 -->
    <view class="search-section" v-if="showSearch">
      <view class="search-card">
        <uni-easyinput
          prefixIcon="search"
          v-model="searchKeyword"
          placeholder="输入姓名或手机号搜索"
          @input="handleSearchInput"
          @confirm="handleSearch"
          @iconClick="handleSearch"
          clearable
        ></uni-easyinput>
      </view>
    </view>

    <!-- 快捷操作区 -->
    <view class="quick-actions">
      <text class="section-title">快捷操作</text>
      <scroll-view class="actions-scroll" scroll-x>
        <view class="actions-list">
          <view class="action-item" @click="navigateToDetail()">
            <view class="action-icon">
              <uni-icons type="plus" size="24" color="#1890FF" />
            </view>
            <text class="action-text">新增会员</text>
          </view>
          <view class="action-item" @click="handleBatchOperation">
            <view class="action-icon">
              <uni-icons type="list" size="24" color="#1890FF" />
            </view>
            <text class="action-text">批量操作</text>
          </view>
          <view class="action-item" @click="handleExportData">
            <view class="action-icon">
              <uni-icons type="download" size="24" color="#1890FF" />
            </view>
            <text class="action-text">数据导出</text>
          </view>
          <view class="action-item" @click="handleMemberStats">
            <view class="action-icon">
              <uni-icons type="bars" size="24" color="#1890FF" />
            </view>
            <text class="action-text">会员统计</text>
          </view>
        </view>
      </scroll-view>
    </view>

    <!-- 会员列表 -->
    <view class="member-list-section">
      <text class="section-title">会员列表</text>
      <scroll-view
        scroll-y
        class="member-list-scroll"
        @refresherrefresh="handleRefresh"
        :refresher-triggered="isRefreshing"
        refresher-enabled
        @scrolltolower="handleLoadMore"
      >
        <view v-if="memberList.length > 0" class="member-list">
          <view
            class="member-card"
            v-for="member in memberList"
            :key="member.id"
            @click="navigateToDetail(member.id)"
          >
            <image class="member-avatar" :src="member.avatar || '/static/images/avatar-placeholder.png'" mode="aspectFill"></image>
            <view class="member-info">
              <view class="info-header">
                <text class="member-name">{{ member.name }}</text>
                <uni-tag :text="member.level || '普通会员'" :inverted="true" type="primary" size="small" />
              </view>
              <view class="info-line">
                <uni-icons type="phone" size="14" color="#999"></uni-icons>
                <text class="phone">{{ member.phone }}</text>
              </view>
              <view class="info-row">
                <view class="info-item">
                  <text class="info-label">余额</text>
                  <text class="info-value">¥{{ (member.balance / 100).toFixed(2) }}</text>
                </view>
                <view class="info-item">
                  <text class="info-label">积分</text>
                  <text class="info-value">{{ member.points }}</text>
                </view>
              </view>
            </view>
            <view class="action-buttons">
              <button class="action-btn" size="mini" @click.stop="handleAdjustBalance(member)">调整余额</button>
              <button class="action-btn" size="mini" @click.stop="handleAdjustPoints(member)">调整积分</button>
            </view>
          </view>
        </view>
        <uni-load-more v-if="memberList.length > 0 || loading" :status="loadingStatus"></uni-load-more>
        <view v-if="memberList.length === 0 && !loading" class="empty-container">
          <uni-icons type="person-filled" size="60" color="#999"></uni-icons>
          <text class="empty-text">暂无会员</text>
        </view>
      </scroll-view>
    </view>

    <!-- 调整余额弹窗 -->
    <uni-popup ref="balancePopupRef" type="dialog">
      <uni-popup-dialog
        mode="input"
        title="调整余额"
        :value="balanceForm.amount"
        placeholder="请输入调整金额"
        :before-close="true"
        @confirm="confirmAdjustBalance"
        @close="closeBalancePopup"
      >
        <template #default>
          <view class="popup-content">
            <view class="member-info-popup">
              <text class="member-name">{{ currentMember?.name }}</text>
              <text class="member-balance">当前余额: ¥{{ currentMember ? (currentMember.balance / 100).toFixed(2) : '0.00' }}</text>
            </view>
            <uni-data-checkbox v-model="balanceForm.type" :localdata="balanceTypeOptions"></uni-data-checkbox>
            <uni-easyinput class="input-amount" v-model="balanceForm.amount" type="digit" placeholder="请输入金额" />
            <uni-easyinput v-model="balanceForm.remark" type="textarea" placeholder="请输入备注(可选)" />
          </view>
        </template>
      </uni-popup-dialog>
    </uni-popup>

    <!-- 调整积分弹窗 -->
    <uni-popup ref="pointsPopupRef" type="dialog">
      <uni-popup-dialog
        mode="input"
        title="调整积分"
        :value="pointsForm.points"
        placeholder="请输入调整积分"
        :before-close="true"
        @confirm="confirmAdjustPoints"
        @close="closePointsPopup"
      >
        <template #default>
          <view class="popup-content">
            <view class="member-info-popup">
              <text class="member-name">{{ currentMember?.name }}</text>
              <text class="member-points">当前积分: {{ currentMember?.points || 0 }}</text>
            </view>
            <uni-data-checkbox v-model="pointsForm.type" :localdata="pointsTypeOptions"></uni-data-checkbox>
            <uni-easyinput class="input-amount" v-model="pointsForm.points" type="number" placeholder="请输入积分" />
            <uni-easyinput v-model="pointsForm.remark" type="textarea" placeholder="请输入备注(可选)" />
          </view>
        </template>
      </uni-popup-dialog>
    </uni-popup>
  </view>
</template>

<script setup lang="ts">
import { ref, reactive, computed } from 'vue';
import { onShow, onPullDownRefresh, onReachBottom } from '@dcloudio/uni-app';
import { fetchMembers, adjustMemberBalance } from '@/api/member';
import type { Member, MemberQuery } from '@/types/member';

const memberList = ref<Member[]>([]);
const searchKeyword = ref('');
const showSearch = ref(false);
const queryParams = reactive({
  page: 1,
  pageSize: 10,
  name: '',
  phone: '',
});

const loading = ref(false);
const isRefreshing = ref(false);
const hasMore = ref(true);
const statistics = reactive({
  totalMembers: 0,
  activeMembers: 0,
  newMembersToday: 0,
  averageBalance: 0,
});

// 余额调整相关
const balancePopupRef = ref<any>(null);
const currentMember = ref<Member | null>(null);
const balanceForm = reactive({
  type: 'charge',
  amount: '',
  remark: '',
});
const balanceTypeOptions = [
  { value: 'charge', text: '增加' },
  { value: 'deduct', text: '减少' },
];

// 积分调整相关
const pointsPopupRef = ref<any>(null);
const pointsForm = reactive({
  type: 'add',
  points: '',
  remark: '',
});
const pointsTypeOptions = [
  { value: 'add', text: '增加' },
  { value: 'reduce', text: '减少' },
];

const loadingStatus = computed(() => {
  if (loading.value) return 'loading';
  return hasMore.value ? 'more' : 'noMore';
});

const getMemberList = async (isRefresh = false) => {
  if (loading.value) return;
  loading.value = true;

  if (isRefresh) {
    queryParams.page = 1;
  }

  try {
    const res = await fetchMembers(queryParams);
    if (isRefresh) {
      memberList.value = res.list;
    } else {
      memberList.value = [...memberList.value, ...res.list];
    }
    hasMore.value = memberList.value.length < res.total;
    
    // 更新统计数据
    if (res.statistics) {
      Object.assign(statistics, res.statistics);
    }
    
    if (queryParams.page) {
      queryParams.page++;
    } else {
      queryParams.page = 2;
    }
  } catch (error) {
    console.error('获取会员列表失败:', error);
    uni.showToast({
      title: '获取会员列表失败',
      icon: 'none'
    });
  } finally {
    loading.value = false;
    isRefreshing.value = false;
    uni.stopPullDownRefresh();
  }
};

const handleSearch = () => {
  // 将搜索关键词分配到name和phone字段
  if (searchKeyword.value) {
    queryParams.name = searchKeyword.value;
    queryParams.phone = searchKeyword.value;
  } else {
    queryParams.name = '';
    queryParams.phone = '';
  }
  getMemberList(true);
};

const handleRefresh = () => {
  isRefreshing.value = true;
  getMemberList(true);
};

const handleLoadMore = () => {
  if (hasMore.value && !loading.value) {
    getMemberList();
  }
};

const navigateToDetail = (id?: number) => {
  const url = id ? `/pages/members/detail?id=${id}` : '/pages/members/detail';
  uni.navigateTo({ url });
};

// 处理调整余额
const handleAdjustBalance = (member: Member) => {
  currentMember.value = member;
  balanceForm.type = 'charge';
  balanceForm.amount = '';
  balanceForm.remark = '';
  balancePopupRef.value.open();
};

const closeBalancePopup = () => {
  balancePopupRef.value.close();
};

const confirmAdjustBalance = async () => {
  if (!currentMember.value) return;
  if (!balanceForm.amount) {
    uni.showToast({ title: '请输入金额', icon: 'none' });
    return;
  }

  const amount = parseFloat(balanceForm.amount);
  if (isNaN(amount) || amount <= 0) {
    uni.showToast({ title: '请输入有效的金额', icon: 'none' });
    return;
  }

  try {
    // 根据类型计算实际金额
    const actualAmount = balanceForm.type === 'charge' ? amount * 100 : -amount * 100;
    
    await adjustMemberBalance(
      currentMember.value.id, 
      actualAmount, 
      balanceForm.remark || `管理员${balanceForm.type === 'charge' ? '充值' : '扣款'}`
    );
    
    uni.showToast({ title: '余额调整成功' });
    balancePopupRef.value.close();
    getMemberList(true);
  } catch (error: any) {
    uni.showToast({ title: error.message || '操作失败', icon: 'none' });
  }
};

// 处理调整积分
const handleAdjustPoints = (member: Member) => {
  currentMember.value = member;
  pointsForm.type = 'add';
  pointsForm.points = '';
  pointsForm.remark = '';
  pointsPopupRef.value.open();
};

const closePointsPopup = () => {
  pointsPopupRef.value.close();
};

const confirmAdjustPoints = async () => {
  if (!currentMember.value) return;
  if (!pointsForm.points) {
    uni.showToast({ title: '请输入积分', icon: 'none' });
    return;
  }

  const points = parseInt(pointsForm.points);
  if (isNaN(points) || points <= 0) {
    uni.showToast({ title: '请输入有效的积分', icon: 'none' });
    return;
  }

  try {
    // 这里需要实现调整积分的API
    // 暂时模拟成功
    uni.showToast({ title: '积分调整成功' });
    pointsPopupRef.value.close();
    getMemberList(true);
  } catch (error: any) {
    uni.showToast({ title: error.message || '操作失败', icon: 'none' });
  }
};

// 防抖搜索
let searchTimer: any = null;
const debouncedSearch = () => {
  if (searchTimer) {
    clearTimeout(searchTimer);
  }
  searchTimer = setTimeout(() => {
    handleSearch();
  }, 300);
};

// 优化搜索体验
const handleSearchInput = () => {
  debouncedSearch();
};

// 切换搜索栏显示
const toggleSearch = () => {
  showSearch.value = !showSearch.value;
};

// 快捷操作处理函数
const handleBatchOperation = () => {
  uni.showToast({
    title: '批量操作功能开发中',
    icon: 'none'
  });
};

const handleExportData = () => {
  uni.showToast({
    title: '数据导出功能开发中',
    icon: 'none'
  });
};

const handleMemberStats = () => {
  uni.showToast({
    title: '会员统计功能开发中',
    icon: 'none'
  });
};

onShow(() => {
  getMemberList(true);
});

// 支持下拉刷新
onPullDownRefresh(() => {
  getMemberList(true);
});

// 支持上拉加载
onReachBottom(() => {
  handleLoadMore();
});
</script>

<style lang="scss" scoped>
.member-container {
  min-height: 100vh;
  background: linear-gradient(180deg, #1890FF 0%, #F0F9FF 30%);
}

.header {
  padding-top: var(--status-bar-height);
  background: linear-gradient(135deg, #1890FF 0%, #40A9FF 100%);
  
  .header-content {
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 20rpx 32rpx;
    
    .header-title {
      font-size: 36rpx;
      font-weight: 600;
      color: #fff;
    }
    
    .header-actions {
      display: flex;
      align-items: center;
    }
  }
}

.overview-section {
  margin: -20rpx 32rpx 32rpx;
  
  .overview-card {
    display: flex;
    background: #fff;
    border-radius: 16rpx;
    padding: 32rpx;
    box-shadow: 0 4rpx 20rpx rgba(24, 144, 255, 0.1);
    
    .overview-item {
      flex: 1;
      display: flex;
      flex-direction: column;
      align-items: center;
      
      .overview-value {
        font-size: 32rpx;
        font-weight: 600;
        color: #1890FF;
        margin-bottom: 8rpx;
      }
      
      .overview-label {
        font-size: 24rpx;
        color: #666;
      }
    }
  }
}

.search-section {
  padding: 0 32rpx 32rpx;
  
  .search-card {
    background: #fff;
    border-radius: 16rpx;
    padding: 24rpx;
    box-shadow: 0 2rpx 12rpx rgba(0, 0, 0, 0.05);
  }
}

.quick-actions {
  padding: 0 32rpx 32rpx;
  
  .section-title {
    font-size: 28rpx;
    font-weight: 600;
    color: #333;
    margin-bottom: 24rpx;
    display: block;
  }
  
  .actions-scroll {
    white-space: nowrap;
    
    .actions-list {
      display: flex;
      gap: 24rpx;
      padding-bottom: 16rpx;
      
      .action-item {
        flex-shrink: 0;
        background: #fff;
        border-radius: 12rpx;
        padding: 24rpx 32rpx;
        display: flex;
        flex-direction: column;
        align-items: center;
        min-width: 120rpx;
        box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.05);
        
        .action-icon {
          margin-bottom: 12rpx;
        }
        
        .action-text {
          font-size: 24rpx;
          color: #333;
          white-space: nowrap;
        }
      }
    }
  }
}

.member-list-section {
  padding: 0 32rpx 32rpx;
  
  .section-title {
    font-size: 28rpx;
    font-weight: 600;
    color: #333;
    margin-bottom: 24rpx;
    display: block;
  }
  
  .member-list-scroll {
    height: 600rpx;
  }
  
  .member-list {
    .member-card {
      display: flex;
      background: #fff;
      border-radius: 16rpx;
      padding: 24rpx;
      margin-bottom: 16rpx;
      box-shadow: 0 2rpx 12rpx rgba(0, 0, 0, 0.05);
      transition: all 0.3s ease;
      
      &:active {
        transform: scale(0.98);
        box-shadow: 0 1rpx 6rpx rgba(0, 0, 0, 0.1);
      }
      
      .member-avatar {
        width: 80rpx;
        height: 80rpx;
        border-radius: 50%;
        margin-right: 24rpx;
        flex-shrink: 0;
      }
      
      .member-info {
        flex: 1;
        display: flex;
        flex-direction: column;
        
        .info-header {
          display: flex;
          justify-content: space-between;
          align-items: center;
          margin-bottom: 12rpx;
          
          .member-name {
            font-size: 28rpx;
            font-weight: 600;
            color: #333;
          }
        }
        
        .info-line {
          display: flex;
          align-items: center;
          font-size: 24rpx;
          color: #666;
          margin-bottom: 12rpx;
          
          .phone {
            margin-left: 8rpx;
          }
        }
        
        .info-row {
          display: flex;
          gap: 32rpx;
          
          .info-item {
            display: flex;
            flex-direction: column;
            
            .info-label {
              font-size: 20rpx;
              color: #999;
              margin-bottom: 4rpx;
            }
            
            .info-value {
              font-size: 24rpx;
              color: #1890FF;
              font-weight: 600;
            }
          }
        }
      }
      
      .action-buttons {
        display: flex;
        flex-direction: column;
        gap: 12rpx;
        margin-left: 16rpx;
        
        .action-btn {
          margin: 0;
          padding: 8rpx 16rpx;
          font-size: 20rpx;
          background: #E6F7FF;
          color: #1890FF;
          border: 1rpx solid #91D5FF;
          border-radius: 8rpx;
          min-width: 120rpx;
          
          &:active {
            background: #BAE7FF;
          }
        }
      }
    }
  }
}

.empty-container {
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  height: 400rpx;
  color: #999;

  .empty-text {
    margin-top: 20rpx;
    font-size: 28rpx;
  }
}

.popup-content {
  padding: 20rpx 0;
  
  .member-info-popup {
    margin-bottom: 30rpx;
    text-align: center;
    
    .member-name {
      font-size: 32rpx;
      font-weight: 600;
      margin-bottom: 10rpx;
      display: block;
      color: #333;
    }
    
    .member-balance, .member-points {
      font-size: 28rpx;
      color: #1890FF;
    }
  }
  
  .input-amount {
    margin: 30rpx 0;
  }
}
</style>